﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Demo.Net.Infrastructure
{
    public static class ConvertHelper
    {
        public static T TryParse<T>(object value, object defaultValue = null)
        {
            try
            {
                return ChangeType<T>(value);
            }
            catch
            {
                return ChangeType<T>(defaultValue);
            }
        }

        public static T ChangeType<T>(object value)
        {
            return (T)ChangeType(value, typeof(T));
        }

        public static object ChangeType(object obj, Type conversionType)
        {
            if (obj == null || obj == DBNull.Value)
            {
                if (!conversionType.IsValueType)
                {
                    return null;
                }

                return Activator.CreateInstance(conversionType);
            }

            Type underlyingType = Nullable.GetUnderlyingType(conversionType);
            if (underlyingType != null)
            {
                return Convert.ChangeType(obj, underlyingType);
            }

            if (typeof(Enum).IsAssignableFrom(conversionType))
            {
                return Enum.Parse(conversionType, obj.ToString());
            }

            if (conversionType == typeof(Guid))
            {
                return new Guid(obj.ToString());
            }

            if (conversionType == typeof(Version))
            {
                return new Version(obj.ToString());
            }

            return Convert.ChangeType(obj, conversionType);
        }

        public static byte[] GetBytes(Stream value)
        {
            using MemoryStream memoryStream = new MemoryStream();
            value.CopyTo(memoryStream);
            return memoryStream.ToArray();
        }

        public static string GetByteSize(decimal file_size)
        {
            if (file_size >= 1024m)
            {
                return GetMB(file_size) ?? "";
            }

            return $"{Math.Round(file_size, 2)}KB";
        }

        private static string GetMB(decimal b)
        {
            b /= 1024m;
            return Math.Round(b, 2) + "MB";
        }
    }
}
